package com.auto.task;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auto.upgrade.utils.AutoUtil;
import com.system.comm.utils.FrameHttpUtil;
import com.system.comm.utils.FrameMapUtil;
import com.system.comm.utils.FrameStringUtil;

/**
 * 程序升级服务
 * @author yuejing
 * @date 2019年12月1日 上午9:21:10
 * @version V1.0.0
 */
public class AutoServiceTask {

	private static final Logger LOGGER = LoggerFactory.getLogger(AutoServiceTask.class);

	/**
	 * 启动服务
	 * @param initialDelay	首次执行的延时时间
	 * @param period		定时执行的间隔时间
	 */
	public void run(int initialDelay, int period) {
		LOGGER.info("初始化 - 程序守护服务的定时任务.");
		ScheduledExecutorService service = Executors.newScheduledThreadPool(20);
		//线程，每隔5秒调用一次
		Runnable runnable = new Runnable() {
			public void run() {
				Map<String, Object> serviceMap = AutoUtil.readServiceInfo();
				Integer open = FrameMapUtil.getInteger(serviceMap, "open");
				if (open == null || open == 0) {
					return;
				}
				List<Map<String, Object>> services = FrameMapUtil.getListMap(serviceMap, "services");
				for (Map<String, Object> map : services) {
					boolean isContinue = true;
					String name = FrameMapUtil.getString(map, "name");
					String start = FrameMapUtil.getString(map, "start");
					//String stop = FrameMapUtil.getString(map, "stop");
					String checkurl = FrameMapUtil.getString(map, "checkurl");
					String premises = FrameMapUtil.getString(map, "premises");
					if (FrameStringUtil.isNotEmpty(checkurl)) {
						LOGGER.info("检测服务[{}], 检测地址[{}]", name, checkurl);
						try {
							FrameHttpUtil.get(checkurl);
							LOGGER.error("{}服务已经启动[{}]", name, checkurl);
							continue;
						} catch (IOException e) {
						}
					}
					if (FrameStringUtil.isNotEmpty(premises)) {
						// 判断前提条件是否达到
						List<String> premiseList = FrameStringUtil.toArray(premises, ",");
						for (String url : premiseList) {
							try {
								FrameHttpUtil.get(url);
							} catch (IOException e) {
								isContinue = false;
								LOGGER.error("请求前置条件[{}]异常: {}", url, e.getMessage());
								break;
							}
						}
						if (!isContinue) {
							continue;
						}
					}
					// 执行启动脚本
					try {
						LOGGER.info("执行start命令中...");
						serviceLinux(start);
						LOGGER.info("执行start命令成功!");
					} catch (Exception e) {
						LOGGER.error("执行start命令失败: " + e.getMessage(), e);
					}
				}
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.SECONDS);
	}

	private void serviceLinux(String shell) throws Exception {
		//int runningStatus = 0;
		//String[] cmdChmod = {"/bin/sh", "-c", shell};
		//runningStatus = Runtime.getRuntime().exec(cmdChmod).waitFor();
		Runtime.getRuntime().exec(shell);
		
		/*ProcessBuilder pb = new ProcessBuilder(shell);
		//设置要运行脚本的目录
		//pb.directory(new File(path));
		
		Process p = pb.start();
		try {
			runningStatus = p.waitFor();
		} catch (InterruptedException e) {
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(
				p.getInputStream()));
		StringBuffer sb = new StringBuffer();
		String line;
		int i=0;
		while ((line = br.readLine()) != null) {
			sb.append("["+(i++)+"]"+line).append("\n");
		}
		LOGGER.info("执行命令状态[{}]和返回结果: {}", runningStatus, sb.toString());*/
		//runningStatus：运行状态，0标识正常。
		/*if (runningStatus != 0) {
			//发布失败调度回写服务端
			fail("执行Shell命令出错");
		} else {
			//发布成功调度回写服务端
			succ("发布成功");
		}*/
	}
}
